package org.xukai.common.util;

import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author lf
 * @desc
 * @date 2019-06-21-16:46
 */
public class SystemUtil {

  private static final Logger logger = LoggerFactory.getLogger(SystemUtil.class);

  public void logTopMemoryConsumers() throws Exception {
    if (new File("/bin/bash").exists() && new File("/bin/ps").exists()
        && new File("/usr/bin/head").exists()) {
      logger.info("logging top memory consumer");

      final java.lang.ProcessBuilder processBuilder =
          new java.lang.ProcessBuilder("/bin/bash", "-c",
              "/bin/ps aux --sort -rss | /usr/bin/head");
      final Process p = processBuilder.start();
      p.waitFor();

      final InputStream is = p.getInputStream();
      final java.io.BufferedReader reader =
          new java.io.BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
      String line = null;
      while ((line = reader.readLine()) != null) {
        logger.info(line);
      }
      is.close();
    }
  }


}
